/**
 * <pre>
 * Copyright:		Copyright(C) 2011-2012, ketayao.com
 * Filename:		SingleThreadedExecution.ketayao.Mutex.java
 * Class:			Mutex
 * Date:			2012-10-18
 * Author:			<a href="mailto:ketayao@gmail.com">ketayao</a>
 * Version          1.1.0
 * Description:		
 *
 * </pre>
 **/
 
package SingleThreadedExecution.ketayao;

/** 
 * 	
 * @author 	<a href="mailto:ketayao@gmail.com">ketayao</a>
 * Version  1.1.0
 * @since   2012-10-18 上午10:06:04 
 */

public class Mutex2 {
	private Thread owner = null;
	private int locks = 0;

	/**  
	 * 描述  
	 */
	public synchronized void locks() {
		Thread me = Thread.currentThread();
		if (locks > 0 && owner != me) {
			try {
				wait();
			} catch (InterruptedException e) {
			}
		}
		
		locks++;
		owner = me;
	}

	/**  
	 * 描述  
	 */
	public synchronized void unlocks() {
		Thread me = Thread.currentThread();
        if (locks == 0 || owner != me) {
            return;
        }
		
		locks--;
		if (locks == 0) {
			owner = null;
			notifyAll();
		}
	}

}
